# -*- coding: utf-8 -*-
"""
cesc wallet bot Project

This project was developed by Seye (cescwalletbot@protonmail.com)

Dependencies:
pip pytelegrambotapi
pip pypng
pip pyqrcode
pip certifi
pip urllib3

"""

import os
import datetime
import json
import sqlite3


def superlog(username, message, reply):
    """    Manages bot global logging."""
    username = str(username)
    superlogfilename = './log/superlog.cwb'
    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    message = str(message)
    reply = str(reply)
    date = str(date)
    if os.path.exists(superlogfilename) is True:
        user_log = open(superlogfilename, 'a+')
        user_log.write('\n' + date + '\t' + username + '\t' + message)
        user_log.write('\n' + date + '\t' + username + '\t' + reply)
    else:
        user_log = open(superlogfilename, 'w')
        user_log.write('\n' + date + '\t' + username + '\t' + message)
        user_log.write('\n' + date + '\t' + username + '\t' + reply)


def userlog(username, message, reply):
    """registers the commands recceived from users."""
    username = str(username)
    superlog(username, message, reply)
    userlogfilename = username + '.cwb'
    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    message = str(message)
    date = str(date)
    if os.path.exists('./log/userlog/' + userlogfilename) is True:
        user_log = open('./log/userlog' + '/' + userlogfilename, 'a+')
        user_log.write('\n' + date + '\t' + message)
    else:
        user_log = open('./log/userlog' + '/' + userlogfilename, 'w')
        user_log.write('\n' + date + '\t' + message)


def lang_pref(message):
    """Saves the language preference in the user preferences file"""
    message_text = message.text.split()
    pref_file = './log/userpref/' + str(message.from_user.username) + '.json'
    if os.path.exists(pref_file) is True:
        pref = json.load(open(pref_file, 'r'))
        pref['lang'] = str(message_text[1])
        json.dump(pref, open(pref_file, 'w'))
    else:
        pref = {'lang': str(message_text[1])}
        json.dump(pref, open(pref_file, 'w'))


def fiat_pref(message):
    """Saves the fiat currency preference in the user preferences file"""
    message_text = message.text.split()
    pref_file = './log/userpref/' + str(message.from_user.username) + '.json'
    if os.path.exists(pref_file) is True:
        pref = json.load(open(pref_file, 'r'))
        pref['fiat'] = str(message_text[1])
        json.dump(pref, open(pref_file, 'w'))
    else:
        pref = {'fiat': str(message_text[1])}
        json.dump(pref, open(pref_file, 'w'))